<template>
  <div class="layout-container">
    <!-- 左侧功能栏 -->
    <div class="sidebar">
      <el-menu router :default-active="$route.path"
               default-active="1"
               class="el-menu-vertical-demo"
               background-color="#f4f4f4"
               text-color="#333"
               active-text-color="#409EFF"
      >
        <el-menu-item index="/chat"><i class="el-icon-menu"></i>对话</el-menu-item>
        <el-menu-item index="/api/goods"><i class="el-icon-document"></i>购买</el-menu-item>
        <el-menu-item index="/home" @click="onUserCenterClick"><i class="el-icon-setting"></i>个人中心</el-menu-item>
      </el-menu>

      <!-- 底部按钮部分 -->
      <div class="sidebar-bottom">
        <el-button type="primary" size="small" @click="editProfile">个人信息修改</el-button>
        <el-button type="danger" size="small" @click="confirmLogout">退出登录</el-button>
      </div>
    </div>

    <!-- 聊天界面 -->
    <div class="chat-container">
      <!-- 用户中心 -->
      <div class="user-center">
        <!-- tokens 显示区域 -->
        <div class="tokens-display">
          <Histogram style="margin-right: 5px;" /> 积分: {{tokens}}
        </div>

<!--        &lt;!&ndash;用户中心下滑栏&ndash;&gt;-->
<!--        <el-dropdown>-->
<!--          <span class="el-dropdown-link">-->
<!--            <i class="el-icon-user"></i> 用户中心<i class="el-icon-arrow-down el-icon&#45;&#45;right"  style="margin-left: 5px;"></i>-->
<!--          </span>-->
<!--          <el-dropdown-menu slot="dropdown">-->
<!--            <el-dropdown-item>修改密码</el-dropdown-item>-->
<!--            <el-dropdown-item>退出</el-dropdown-item>-->
<!--          </el-dropdown-menu>-->
<!--        </el-dropdown>-->
      </div>

      <h2>聊天界面</h2>
      <div class="chat-window">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.sender]"
        >
          <!-- 用户消息 -->
          <div v-if="message.sender === 'user'" class="user-message">
            <div class="message-bubble">{{ message.text }}</div>
            <img src="@/assets/user1.png" alt="用户头像" class="avatar" />
          </div>
          <!-- 系统消息 -->
          <div v-else class="system-message">
            <img src="@/assets/frank.png" alt="机器人头像" class="avatar" />
            <div class="message-text" v-html="renderMessage(message.text)"></div>
          </div>
        </div>
        <!-- 当前正在接收的消息 -->
        <div v-if="currentMessage" class="system-message">
          <img src="@/assets/frank.png" alt="机器人头像" class="avatar" />
          <div class="-text" v-html="renderMessage(currentMessage)"></div>
        </div>
      </div>
      <el-form @submit.prevent="onSubmit" class="input-area">
        <div class="input-container">
          <el-input
              v-model="question"
              placeholder="请输入您的问题"
              class="input-field"
              @keydown.enter.native="onSubmit"
              :disabled="!isWebSocketOpen"
          />
          <el-button
              type="primary"
              @click="onSubmit"
              class="submit-button"
              :disabled="!isWebSocketOpen"
          >
            <el-icon class="submit-icon"><Promotion /></el-icon> <!-- 替换发送文字为图标 -->
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>


<script>
import { marked } from "marked";
import hljs from "highlight.js"; // 引入 highlight.js
import 'highlight.js/styles/atom-one-dark.css';

import { Promotion, Histogram } from '@element-plus/icons-vue';
import axios from 'axios';
import PricingTable from "@/components/GoodsTable";

export default {
  components: {
    Promotion,
    Histogram,
  },
  data() {
    return {
      question: "",
      messages: [],
      websocket: null,
      isWebSocketOpen: false,
      currentMessage: "",
      messageTimeout: null,
      tokens: 0,
      username: ""
    };
  },
  mounted() {
    console.log("Component mounted");
    this.username = localStorage.getItem('username');
    console.log("Retrieved username:", this.username);
    if (this.username) {
      this.initWebSocket();
      console.log("Calling fetchTokens...");
      this.fetchTokens();
      setInterval(() => {
        this.fetchTokens();
      }, 5000);
    } else {
      console.error('Username is not found in sessionStorage.');
    }
    this.applyHighlighting(); // 在 mounted 钩子中调用代码高亮
  },
  updated() {
    this.applyHighlighting(); // 在 updated 钩子中调用代码高亮
  },

  methods: {
    async fetchUserInfo() {
      console.log('Fetching user information');

      try {
        // 从 localStorage 获取用户名
        const username = localStorage.getItem('username');
        if (!username) {
          this.$message.error('用户名不存在');
          return;
        }

        // 发送 GET 请求以获取用户信息
        const response = await axios.get('http://localhost:8090/user/userInfo', {
          params: { username }
        });

        // 检查响应数据是否存在
        if (response && response.data) {
          // 处理响应数据
          if (response.data.code === 0) {
            const { email, password, tokens } = response.data.data || {};

            // 检查用户数据是否存在
            if (email && password && tokens) {
              // 将用户信息存储到 localStorage
              localStorage.setItem('email', email);
              localStorage.setItem('password', password);
              localStorage.setItem('tokens', tokens);

              // 显示成功消息
              this.$message.success('用户信息已更新');
            } else {
              // 当用户数据为空时，显示错误消息
              this.$message.error('用户数据未定义或为空');
            }
          } else {
            // 处理后端返回的错误消息
            this.$message.error('获取用户信息失败：' + response.data.message);
          }
        } else {
          // 当响应为空时，显示错误消息
          this.$message.error('响应数据未定义或为空');
        }
      } catch (error) {
        // 捕获异常并显示错误消息
        console.error('Error fetching user info:', error);
        this.$message.error('请求用户信息时出错');
      }
    },

    // 点击个人中心时调用此方法
    onUserCenterClick() {
      this.fetchUserInfo();
    },
    editProfile() {
      this.$message('个人信息修改功能尚未实现！');
    },
    confirmLogout() {
      this.$confirm('确定要退出吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        });
      });
    },
    logout() {

      localStorage.clear();

      this.$message.success('已退出登录');
      this.$router.push('/login');
    },

    applyHighlighting() {
      this.$nextTick(() => {
        hljs.highlightAll(); // 调用 highlight.js 的高亮方法
      });
    },
    initWebSocket() {
      const wsUrl = `ws://localhost:8090/xinghuo/chat-websocket?username=${encodeURIComponent(this.username)}`;
      this.websocket = new WebSocket(wsUrl);

      this.websocket.onopen = () => {
        console.log("WebSocket connection opened.");
        this.isWebSocketOpen = true;
      };

      this.websocket.onmessage = this.handleWebSocketMessage;
      this.websocket.onerror = this.handleWebSocketError;
      this.websocket.onclose = () => {
        console.log("WebSocket connection closed.");
        this.isWebSocketOpen = false;
      };
    },
    async fetchTokens() {
      console.log("Attempting to fetch tokens with username:", this.username);
      try {
        const response = await axios.get('http://localhost:8090/user/tokens', {
          params: { username: this.username }
        });
        console.log("Fetched tokens:", response.data);
        if (response.data.code === 0) {
          this.tokens = response.data.data;
        } else {
          console.error('Failed to fetch tokens:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching tokens:', error);
      }
    },
    onSubmit() {
      if (this.question && this.isWebSocketOpen) {
        this.messages.push({ text: this.question, sender: "user" });
        this.websocket.send(this.question);
        this.question = "";
        this.scrollToBottom();
      } else if (!this.isWebSocketOpen) {
        console.error("WebSocket is not open. Unable to send message.");
      }
    },
    // handleWebSocketMessage(event) {
    //   let msg = event.data.trim();
    //
    //   if (msg) {
    //     clearTimeout(this.messageTimeout);
    //
    //     if (this.isCodeMessage(msg)) {
    //       this.currentMessage += `\n\`\`\`javascript\n${msg}\n\`\`\`\n`;
    //     } else {
    //       this.currentMessage += msg;
    //     }
    //
    //     this.messageTimeout = setTimeout(() => {
    //       this.messages.push({ text: this.currentMessage, sender: "system" });
    //       this.currentMessage = "";
    //       this.scrollToBottom();
    //     }, 2000);
    //   }
    // },
    handleWebSocketMessage(event) {
      let msg = event.data.trim();

      if (msg) {
        clearTimeout(this.messageTimeout);

        if (this.isCodeMessage(msg)) {
          this.currentMessage += `\n${msg}\n`;
        } else {
          this.currentMessage += msg;
        }

        this.messageTimeout = setTimeout(() => {
          const renderedMessage = this.renderMessage(this.currentMessage);
          this.messages.push({ text: renderedMessage, sender: "system" });
          this.currentMessage = "";
          this.scrollToBottom();
        }, 2000);
      }
    },
    isCodeMessage(message) {
      const codeKeywords = [
        "function", "const", "let", "var", "if", "else", "for",
        "while", "return", "{", "}", ";"
      ];
      return codeKeywords.some((keyword) => message.includes(keyword));
    }
    ,
    renderMessage(message) {
      return marked(message, {
        highlight: function (code, lang) {
          if (hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value;
          }
          return hljs.highlightAuto(code).value; // 自动检测语言并高亮
        },
        gfm: true, // 启用 GitHub 风格的 Markdown
        breaks: true, // 支持段内换行
        smartypants: true, // 更好的标点符号处理
      });
    }

    ,
    handleWebSocketError(event) {
      console.error("WebSocket error observed:", event);
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatWindow = this.$el.querySelector(".chat-window");
        chatWindow.scrollTop = chatWindow.scrollHeight;
      });
    },
  },
};
</script>

<style scoped>

.sidebar-bottom {
  display: flex;
  justify-content: space-between; /* 按钮水平排列，左右分布 */
  align-items: center;
  padding-top: 20px;
  width: 100%;
}

.sidebar-bottom .el-button {
  flex: 1;
  margin-right: 10px; /* 按钮之间的间距 */
}

.sidebar-bottom .el-button:last-child {
  margin-right: 0; /* 取消最后一个按钮的右侧间距 */
}

.el-dropdown-link {
  cursor: pointer;
  color: #451b56;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.layout-container {
  display: flex;
  height: 100vh;
}

.sidebar {
  width: 240px;
  background-color: #f4f4f4;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 使左侧栏内容和底部按钮上下分布 */
}

.chat-container {
  flex: 1;
  padding: 20px;
  position: relative;
}

.user-center {
  position: absolute;
  top: 10px;
  right: 80px;
  display: flex;
  align-items: center;
  gap: 50px;
}

.tokens-display {
  font-size: 16px;
  color: #451b56;
  display: flex;
  align-items: center;
  gap: 5px;
}

.user-message {
  display: flex;
  align-items: center; /* Aligns the avatar and message bubble vertically */
  margin-top: 12px;
  justify-content: flex-end;
  margin-right: 20px;
  gap: 10px; /* Adds space between the avatar and the bubble */
}

.system-message {
  display: flex;
  align-items: flex-start;
  margin-top: 12px;
  margin-left: 20px;
}

.message-bubble {
  background-color: #cabde1;
  color: #000;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 10px 15px;
  border-radius: 20px;
  font-size: 16px;
  max-width: 80%; /* 将最大宽度调整为80% */
  word-wrap: break-word;
}

.message-text {
  background-color: #ffffff;/*#e3f2fd*/
  color: #333;
  border-radius: 10px;
  padding: 10px 15px;
  font-size: 16px;
  max-width: 80%; /* 同样调整为80% */
  word-wrap: break-word;

}

.input-field {
  border-radius: 30px;
  border: 1px solid #ffffff;
  padding-right: 20px;
  font-size: 16px;
  height: 45px;
  max-width: calc(100% - 90px);
  background-color: #ffffff;
  padding-left: 20px;
}

.submit-button {
  background-color: rgba(183, 162, 215, 0.8);
  border: none;
  border-radius: 20px; /* 改成圆角正方形 */
  width: 45px;
  height: 45px;
  position: absolute;
  right: 50px;
  top: 91.5%;
  transform: translateY(-50%);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.submit-icon {
  font-size: 24px;
}
.message-text code {
  background-color: #f5f5f5;
  color: #c7254e;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
  margin: 0 2px; /* 减少左右间距 */
}


.message-text pre {
  background-color: #282c34;
  color: #abb2bf;
  padding: 10px;
  border-radius: 8px;
  overflow: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 10px; /* 设置合适的字体大小 */
  margin: 5px 0; /* 增加代码块的上下间距 */
}

.chat-window {
  height: calc(100vh - 200px); /* 保留空间给输入框 */
  overflow-y: auto;
  padding-bottom: 20px;
  scroll-behavior: smooth; /* 平滑滚动效果 */
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
